package com.letv.app.ljodfh.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.letv.app.ljodfh.base.Cache;
import com.letv.app.ljodfh.base.Constances;
import com.letv.app.ljodfh.beans.NewsClickCountBean;
import com.letv.app.ljodfh.beans.NewsIdBean;
import com.letv.app.ljodfh.beans.NewsListClickRequestBean;
import com.letv.app.ljodfh.beans.NewsListClickVo;
import com.letv.app.ljodfh.beans.Titles;
import com.letv.app.ljodfh.http.AbsNetCallBack;
import com.letv.app.ljodfh.ui.adapter.HomePagerAdapter;
import com.letv.app.ljodfh.ui.util.IListShowData;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.letv.app.ljodfh.R;
import com.letv.app.ljodfh.beans.NewsItem;
import com.letv.app.ljodfh.http.AbsListNetCallback;
import com.letv.app.ljodfh.http.NetUtils;
import com.letv.app.ljodfh.ui.adapter.CommonFrgAdapter;
import com.letv.app.ljodfh.ui.util.RBaseItemDecoration;
import com.letv.app.ljodfh.ui.utils.SkipUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by raoweiwei on 2017/8/3.
 */

public class CommonFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.common_frg_refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    private CommonFrgAdapter mAdapter;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_common_frg, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(1));
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            mRefreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    private void getData() {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), channelUrl, mPageNo, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }

                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
//                initData(newsItems, getPageResponse().getData().getTemplate());
                requestNewsClickCount(newsItems, getPageResponse().getData().getTemplate());
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }
    private List<NewsItem> newsItems;
    //    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isRefresh = false;
    /**
     * 获取新闻列表点击量
     *
     * @param list
     * @param isTemplate
     */
    private void requestNewsClickCount(List<NewsItem> list, final int isTemplate) {
        newsItems = new ArrayList<>();
        newsItems.addAll(list);
        List<NewsIdBean> newsIdList = new ArrayList<>();
        NewsIdBean newsBean;
        for (int i = 0; i < list.size(); i++) {
            String type = "10";//默认不返回点击量
//            if (list.get(i) instanceof NewsItem) {
                NewsItem item = (NewsItem) list.get(i);
                newsBean = new NewsIdBean();
                newsBean.setId(item.getUrlNewsId());
                switch (item.getNewsType()) {
                    case Constances.NEWS_TYPE_GRAPHIC:
                    case Constances.NEWS_TYPE_AUDIO:
                    case Constances.NEWS_TYPE_VIDEO:
                        //新闻详情
                        type = "0";
                        break;
                    case Constances.NEWS_TYPE_LIVE:
                        //直播详情
                        type = "1";
                        break;
                }
                newsBean.setType(type);
                newsIdList.add(newsBean);
//            } else {
//                newsBean = new NewsIdBean();
//                newsBean.setId("1");
//                newsBean.setType(type);
//                newsIdList.add(newsBean);
//            }
        }
        if (ListUtils.isListValued(newsIdList)) {
            NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
            requestBean.setNewsIds(newsIdList);
            Gson gson = new Gson();
            String newsId = gson.toJson(requestBean);
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
            NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                @Override
                public void onSuc(NewsListClickVo newsListClickVo) {
                    if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                        List<NewsClickCountBean> countList = newsListClickVo.getResult();
                        for (int i = 0; i < countList.size(); i++) {
//                            if (newsItems.get(i) instanceof NewsItem) {
                                NewsItem item = (NewsItem) newsItems.get(i);
                                if (countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                    ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                }
//                            }
                        }
                    }

                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    initData(newsItems,isTemplate);
                    isRefresh = false;
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }
            });
        }
    }

    private void initData(List<NewsItem> newsItems, int template) {
        if (mAdapter == null) {
            mAdapter = new CommonFrgAdapter(getActivity(), newsItems, template).setItemInternalClick(itemClick);
            mRecyclerView.setAdapter(mAdapter);
        }
        if (mPageNo == 0) {
            mAdapter.setData(newsItems);
        } else {
            mAdapter.addDatas(newsItems);
        }
        mPageNo++;
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(mPageNo >= mPageAll ? false : true);
    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            SkipUtil.skipWithNewsItem(getActivity(), (NewsItem) mAdapter.getItem(position), Cache.getInstance().getCurrentChannelId());
        }
    };


}
